package com.client;

import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.helpers.DOMUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.namespace.QName;
import java.util.List;

/**
 * 自定义拦截器验证用户名密码
 */
public class ClientInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
    private final String account;
    private final String password;

    //发送请求前阶段进行拦截
    public ClientInterceptor(String account, String password) {
        super(Phase.PREPARE_SEND);
        this.account = account;
        this.password = password;
    }

    @Override
    public void handleMessage(SoapMessage soapMessage) throws Fault {
        List<Header> headers = soapMessage.getHeaders();
        Document doc = DOMUtils.createDocument();
        Element auth = doc.createElementNS("http://service.server.webService.web.boot.qm.com/", "SecurityHeader");
        Element mAccount = doc.createElement("account");
        Element mPassword = doc.createElement("password");

        mAccount.setTextContent(account);
        mPassword.setTextContent(password);

        auth.appendChild(mAccount);
        auth.appendChild(mPassword);

        headers.add(0, new Header(new QName("SecurityHeader"), auth));
    }
}